package com.example.springbootcourse.service.impl;

import com.example.springbootcourse.mapper.CourseMapper;
import com.example.springbootcourse.mapper.CurelationMapper;
import com.example.springbootcourse.pojo.Course;
import com.example.springbootcourse.pojo.Curelation;
import com.example.springbootcourse.pojo.CurelationExample;
import com.example.springbootcourse.req.CourseReq;
import com.example.springbootcourse.service.CourseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    CurelationMapper curelationMapper;

    @Override
    public List<Course> queryCourse() {
        return courseMapper.selectByExample(null);
    }

    @Override
    public void saveCourse(Course course) {

        if (StringUtils.isEmpty(course.getId())){
            course.setStatus("1");
            course.setId(String.valueOf(Math.random()).substring(2, 10));
            courseMapper.insert(course);
        }else {
            courseMapper.updateByPrimaryKey(course);
        }


    }

    @Override
    public void delCourse(String id) {
        courseMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void arranging(CourseReq req) {
        Course course = courseMapper.selectByPrimaryKey(req.getId());
        course.setId(req.getId());
        course.setCourseroom(StringUtils.join(req.getCourseroom(),","));
        course.setCoursedate(StringUtils.join(req.getDate1(),",")+StringUtils.join(req.getDate2(),","));
        courseMapper.updateByPrimaryKey(course);


    }

    @Override
    public void listening(Curelation curelation) {

        // 判断课程是否有听课人员
        CurelationExample example = new CurelationExample();
        CurelationExample.Criteria criteria = example.createCriteria();
        criteria.andCourseidEqualTo(curelation.getCourseid());
        List<Curelation> curelations = curelationMapper.selectByExample(example);


        if (curelations != null && !curelations.isEmpty()) {
            // 课程已经有听课人员

            Curelation curelation1 = curelations.get(0);
            curelation1.setUserid(curelation.getUserid());
            curelationMapper.updateByPrimaryKey(curelation1);

        }else {
            Course course = courseMapper.selectByPrimaryKey(curelation.getCourseid());
            curelation.setType(course.getCoursename());
            curelation.setId(String.valueOf(Math.random()).substring(2, 10));
            curelationMapper.insert(curelation);
        }



    }

    @Override
    public List<Curelation> queryCurelation() {

        List<Curelation> curelations = curelationMapper.selectByExample(null);

        return curelations;
    }

    @Override
    public void delCurelation(String id) {
        curelationMapper.deleteByPrimaryKey(id);
    }


}
